<?php

/**
 * Created by PhpStorm.
 * User: admin
 * Date: 2017/6/21
 * Time: 15:25
 */
namespace ElementVip\JwOms\Services;

use Carbon\Carbon;
use ElementVip\Component\Brand\Models\Brand;
use ElementVip\Component\Order\Models\Order;
use ElementVip\Component\Shipping\Models\Shipping;
use ElementVip\Component\Shipping\Models\ShippingMethod;
use ElementVip\JwOms\Models\OmsSyncLog;
use ElementVip\JwOms\Models\OmsUploadLog;

class OrderService
{
    protected $uploadLog;

    public function __construct()
    {
        $this->uploadLog = new OmsUploadLog();
    }

    /**
     * 获取商城已支付订单数据
     * @return array
     */
    public function getOrdersData()
    {
        $tag = $this->uploadLog->getLastTag('Order');
        $orders = Order::where('pay_time', '>', $tag)->where('status', 2)->with('items')->get();
        $data = '';
        $lastTag = Carbon::now();

        if (count($orders) > 0) {
            foreach ($orders as $key => $item) {
                $address = explode(' ', $item->address_name);

                $data_head = 'SHHDRDNNEW';
                $warehouse = '';
                $shipment_id = $item->order_no;   //订单号
                $company = 'JW';
                $customer_name = $this->getUserName($item);  //卖家昵称
                $order_amount = $item->total / 100; //订单金额
                $order_shipping_fee = $item->real_freight / 100; //运费
                $ship_to_name = $item->accept_name;   //收货人
                $ship_to_conntry = '中国';
                $ship_to_province = $address[0];
                $ship_to_city = $address[1];
                $ship_to_district = isset($address[2]) ? $address[2] : '';
                $ship_to_zipcode = '';    //邮编
                $ship_to_address = $item->address; //详细地址
                $carrier = '';    //快递公司
                $ship_to_phone = '';  //收货人电话
                $ship_to_mobile = $item->mobile;  //手机
                $create_time = $item->created_at;
                $remark = $item->message;     //用户留言
                $order_type = '官网订单'; //订单类型
                $pay_type = $item->payments->first()->channel; //支付方式
                $pay_time = $item->pay_time;
                $pay_transaction_no = $item->payments->first()->channel_no;

                $head = $data_head . ';' . $warehouse . ';' . $shipment_id . ';' . $company . ';' . $customer_name
                    . ';' . $order_amount . ';' . $order_shipping_fee . ';' . $ship_to_name . ';' . $ship_to_conntry
                    . ';' . $ship_to_province . ';' . $ship_to_city . ';' . $ship_to_district . ';' . $ship_to_zipcode
                    . ';' . $ship_to_address . ';' . $carrier . ';' . $ship_to_phone . ';' . $ship_to_mobile . ';'
                    . $create_time . ';' . $remark . ';' . $order_type . ';' . $pay_type . ';' . $pay_time . ';' . $pay_transaction_no . ';' . "\r";

                $items = '';

                foreach ($item->items as $k => $val) {
                    $model = $val->getModel();
                    /*if ($model) {
                        if ($val->type == 'ElementVip\Component\Product\Models\Product') {
                            $brand = Brand::find($model->goods->brand_id)->name;
                        } else {
                            $brand = Brand::find($model->brand_id)->name;
                        }
                    } else {
                        $brand = '';
                    }*/
                    if($model)
                    {
                        $data_head = 'SHDTLDNNEW';
                        $shipment_id = $item->order_no;
                        $company = 'JW';  //品牌名称
                        $sku = $model->sku;
                        $upc_code = '';
                        $sale_price = $val->total / $val->quantity / 100;
                        $goods_number = $val->quantity;

                        $spc = explode(' ', $val->item_meta['specs_text']);
                        $color = $spc[0];
                        $size = $spc[1];

                        $items = $items . $data_head . ";" . $shipment_id . ";" . $company . ";" . $sku . ';'
                            . $upc_code . ';' . $sale_price . ';' . $goods_number . ';' . $color . ';' . $size . ';' . "\r";
                    }
                }
                $data = $data . $head . $items;
            }
        }
        \Log::info('进入了获取订单数据');
        return ['data' => $data, 'lastTag' => $lastTag];
    }

    private function getUserName($item)
    {
        $name = '';
        if ($user = $item->user) {
            if ($user->nick_name) {
                $name = $user->nick_name;
            } elseif ($user->name) {
                $name = $user->nick_name;
            } else {
                $name = $user->mobile;
            }
        }
        return $name;
    }

    /**
     * 同步订单发货状态
     * @param $file
     */
    public function orderShip($file)
    {
        $fileUrl = '/storage/' . strstr($file, 'oms');
        $lines = file($file);
        $failed = [];
        $success = [];

        foreach ($lines as $key => $item) {
            $data = explode(';', $item);
            $head = $data[0];
            $order_no = $data[2];
            $ship = $data[5];
            $ship_date_time = $data[4];
            $express_no = $data[6];

            if ($head == 'SHHDRUP') {
                if (!$order = Order::where('order_no', $order_no)->first()) {
                    //订单不存在,记录日志
                    $failed[] = '订单 ' . $order_no . ' 不存在';
                    continue;
                }

                if ($order->status == Order::STATUS_DELIVERED) {
                    //订单已经发货,记录日志
                    $failed[] = '订单 ' . $order_no . ' 已经发货';

                    continue;
                }

                if (!$method_id = $this->ship($ship)) {
                    //快递公司不存在,记录日志
                    $failed[] = '订单 ' . $order_no . ' 的快递公司 ' . $ship . ' 匹配不到';
                    continue;
                }
                $shippingData = [
                    'method_id' => $method_id,
                    'order_id' => $order->id,
                    'tracking' => $express_no,
                    'delivery_time' => $ship_date_time
                ];

                if ($shipping = Shipping::create($shippingData)) {
                    $order->status = Order::STATUS_DELIVERED;
                    $order->send_time = $ship_date_time;
                    $order->distribution_status = 1;
                    $order->distribution = $method_id;
                    $order->save();

                    $success[] = '订单 ' . $order_no . ' 同步发货状态成功';
                }
            }
        }

        if (count($failed) > 0 OR count($success) > 0) {
            OmsSyncLog::create([
                'type' => 'OrderSendShip',
                'file' => $fileUrl,
                'success_message' => $success,
                'failed_message' => $failed
            ]);
        }

    }

    private function ship($code)
    {

        switch ($code) {
            case 'sf':
                $ship = 'shunfeng';
                break;
            case 'ems':
                $ship = 'ems';
                break;
            case 'sto':
                $ship = 'shentong';
                break;
            case 'yto':
                $ship = 'yuantong';
                break;
            case 'zto':
                $ship = 'zhongtong';
                break;
            case 'zjs':
                $ship = 'zhaijisong';
                break;
            case 'yunda':
                $ship = 'yunda';
                break;
            case 'htky':
                $ship = 'huitongkuaidi';
                break;
            case 'ttkdex':
                $ship = 'tiantian';
                break;
            case 'dbl':
                $ship = 'debangwuliu';
                break;
            default:
                $ship = 'shunfeng';
        }

        if ($shipMethod = ShippingMethod::where('code', $ship)->first()) {
            return $shipMethod->id;
        }

        return false;
    }
}